package cmd

import (
	"fiberx/internal/dao"
	"fiberx/internal/global"
	"fiberx/internal/global/configs"
	"fiberx/internal/router"
	"fiberx/internal/version"
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var (
	vers bool
	mode string
)

// startCmd represents the start command
var RootCmd = &cobra.Command{
	Use:   "fiberx",
	Short: "fiberx",
	Long:  `fiberx`,
	RunE:  startRun,
}

func startRun(cmd *cobra.Command, args []string) error {
	if vers {
		fmt.Println(version.FullVersion())
		os.Exit(1)
	}

	if mode == "" {
		mode = configs.C.Server.Runmode
	}

	// 启动
	router.Engine(mode)
	return nil
}

func init() {
	RootCmd.Flags().StringVarP(&mode, "mode", "m", "", "debug or release")
	RootCmd.PersistentFlags().BoolVarP(&vers, "version", "v", false, "print version")

	// 初始化根命令，这一步会自动添加 completion 命令
	RootCmd.CompletionOptions.DisableDefaultCmd = true
	// 手动移除 completion 命令
	for i, cmd := range RootCmd.Commands() {
		if cmd.Name() == "completion" {
			RootCmd.RemoveCommand(RootCmd.Commands()[i])
			break
		}
	}

	// 初始化dao
	dao.SetDefault(global.DB)
}
